using Microsoft.EntityFrameworkCore;
using Project_Schedule.Model.Entities;
using Project_Schedule.Model.EntitiesHelper;

namespace Project_Schedule.Model;

public static class EFAuxiliary
{
    public static async Task Ef_Core_SystemInitialization(IConfiguration configuration)
    {
        var configSql = configuration.GetSection("Sql:Default");
        var configKey = configuration.GetSection("PwdKey:Default");
        DataBase = configSql.GetSection("Catalog").Value ?? "NULL";
        Pwd = configSql.GetSection("PWD").Value ?? "NULL";
        User = configSql.GetSection("User").Value ?? "NULL";
        Port = configSql.GetSection("PORT").Value ?? "NULL";
        Source = configSql.GetSection("Source").Value ?? "NULL";
        RsaEncryptUtil.Pub = configKey.GetSection("PubKey").Value;
        RsaEncryptUtil.PriPkcs8 = configKey.GetSection("PriKey").Value;
        var efInit = new CreateEFCoreDataBase();
        await efInit.EFModelInitialization();
        Console.WriteLine(@"__   _______ ____          ");
        Console.WriteLine(@"\ \ / /_   _/ __ \   /\    ");
        Console.WriteLine(@" \ V /  | || |  | | /  \   ");
        Console.WriteLine(@"  > <   | || |  | |/ /\ \  ");
        Console.WriteLine(@" / . \ _| || |__| / ____ \ ");
        Console.WriteLine(@"/_/ \_\_____\____/_/    \_\");
    }

    public static string? DataBase { get; private set; } = null!;
    public static string? Pwd { get; private set; } = null!;
    public static string? User { get; private set; } = null!;
    public static string? Port { get; private set; } = null!;
    public static string? Source { get; private set; } = null!;


    public static int Major { get; set; } = 8;
    public static int Minor { get; set; } = 0;
    public static int Build { get; set; } = 5;


}

public class CreateEFCoreDataBase
{
    public async Task EFModelInitialization()
    {
        try
        {
            await using (var db = new DataDbContext())
            {
                var init = await db.BackgroundUsers?.FirstOrDefaultAsync(e =>
                    e.Account == "admin");
                if (init is null)
                    throw new Exception();
            }
        }
        catch (Exception)
        {
            await using (var db = new DataDbContext())
            {
                await db.Database.EnsureCreatedAsync();
                await db.BackgroundUsers!.AddAsync(new Background_User
                {
                    Account = "admin",
                    UserName = "admin",
                    Password = RsaEncryptUtil.RSAEncrypt("2873"),
                    Auth = Background_User_Auth_Enum.Admin
                });
                await db.SaveChangesAsync();
            }
        }
    }
}